package han.message;

import com.han.http.client.paramter.RequestHeader;
import com.han.http.fetch.Fetcher;
import han.proof.SmartqqProof;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.han.http.util.Print.printlnInfo;

/**
 * @author: Han
 * @date: 2018/7/17 9:42
 * @dscription: 每分钟发送一次在线请求, 保持在线
 */
public class KeepOnline implements Runnable {

    private static Logger logger = LoggerFactory.getLogger(KeepOnline.class);

    private boolean isRunning;

    public KeepOnline() {
        isRunning = true;
    }

    @Override
    public void run() {
        while (isRunning) {
            logger.info("保持在线状态");
            try {
                getOnlineStatus();
            } catch (Exception e) {
                logger.error("发送保持在线状态请求失败");
                logger.info(e.toString());
                StackTraceElement[] stackTraceElements = e.getStackTrace();
                for (StackTraceElement stackTraceElement : stackTraceElements) {
                    logger.error(stackTraceElement.toString());
                }
            }
            try {
                Thread.sleep(1000 * 60);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取在线状态,如果不获取,接收不到信息
     *
     * @throws Exception 抛出异常
     */
    private void getOnlineStatus() throws Exception {
        SmartqqProof smartqqProof = SmartqqProof.getInstance();

        String url = "https://d1.web2.qq.com/channel/get_online_buddies2?vfwebqq=" + smartqqProof.getVfwebqq() +
                "&clientid=53999199&psessionid=" + smartqqProof.getPsessionid() + "&t=" + System.currentTimeMillis();
        String cookie = smartqqProof.getCookie().replaceAll("; uin=[o]?", "; uin=o");
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "d1.web2.qq.com"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36"),
                new RequestHeader("Content-Type", "utf-8"),
                new RequestHeader("Accept", "*/*"),
                new RequestHeader("Referer", "https://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2"),
                new RequestHeader("Accept-Encoding", "gzip, deflate"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
                new RequestHeader("Cookie", cookie)
        };
        Fetcher fetcher = new Fetcher();
        fetcher.getPageInfoByGet(url, requestHeaders, 1000 * 30, 1000 * 30, false, null);
    }
}
